package repository

import (
	"gorm.io/gorm"
	"shop-bean/model"
	"shop-common/utils/queryWrapper"
)

type ITransfeeRepository interface {
	CreateBatch(db *gorm.DB, transports []*model.Transfee) error
	DeleteBatch(db *gorm.DB, transfees []*model.Transfee) error
	Find(db *gorm.DB, pair *queryWrapper.WherePair) (transfees []*model.Transfee, err error)
}

type TransfeeRepository struct {
}

func NewTransfeeRepository() ITransfeeRepository {
	return &TransfeeRepository{}
}

func (r *TransfeeRepository) CreateBatch(db *gorm.DB, transports []*model.Transfee) error {
	return db.Create(&transports).Error
}

func (r *TransfeeRepository) DeleteBatch(db *gorm.DB, transfees []*model.Transfee) (err error) {
	for _, transfee := range transfees {
		if err := db.Delete(&model.Transfee{}, transfee.TransfeeId).Error; err != nil {
			return err
		}

		if len(transfee.CityList) > 0 {
			err = db.Delete(&transfee.CityList).Error
			if err != nil {
				return err
			}
		}
	}

	return nil
}

func (r *TransfeeRepository) Find(db *gorm.DB, pair *queryWrapper.WherePair) (transfees []*model.Transfee, err error) {
	tx := db.Preload("CityList").Model(&model.Transfee{})
	return transfees, queryWrapper.ReuseWherePair(tx, pair).Find(&transfees).Error
}
